package lance.honeydew.util;

import java.nio.charset.Charset;
import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;

import org.apache.log4j.Logger;
import org.apache.tomcat.util.codec.binary.Base64;

public class CipherUtil {

	private static final Logger logger = Logger.getLogger(CipherUtil.class);
	
	private static String str = "TESTTESTTESTTEST"; //必須16個字元
	private static byte[] key = str.getBytes();
	
	public static String encrypt(String strToEncrypt) {
		
		try {
			
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            final SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            final String encryptedString = Base64.encodeBase64String(cipher.doFinal(strToEncrypt.getBytes()));		
			return encryptedString;
			
		} catch(Exception e) {
			e.printStackTrace();
			logger.debug(e);
		}
		
		return "";
	}
	
	public static String decrypt(String strToDecrypt) {
		
		try {
			
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
			final SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
			cipher.init(Cipher.DECRYPT_MODE, secretKey);
			final String decryptedString = new String(cipher.doFinal(Base64.decodeBase64(strToDecrypt)));
			return decryptedString;
			
		} catch(Exception e) {
			e.printStackTrace();
			logger.debug(e);
		}
		
		return "";
	}
}
